import { UploadOutlined } from "@ant-design/icons";
import { ProCard } from "@ant-design/pro-components";
import { Button, Space, Upload } from 'antd';
import { useState } from "react";
import { Input } from 'antd';
import Parser from "./parse";

const { TextArea } = Input;

export default function TwineTool() {
  const [curFile, setCurFile] = useState(null)

  const [curFileName, setCurFileName] = useState('')

  const [inputContent, setInputContent] = useState('')
  const [outputContent, setOutputContent] = useState('')

  const parser = new Parser()

  const handleChangeFile = (obj: any) => {
    if (obj.file) {
      console.log(obj.file)
      setCurFile(obj.file)
      setCurFileName(obj.file?.name)
    }
  }

  const readToCsvData = () => {
    if (!curFile) {
      return
    }
    parser.content = inputContent
    const rows = parser.parseToCsvData()
    setOutputContent(JSON.stringify(rows))
  }

  const downloadCsvData = () => {
    if (!curFile) {
      return
    }
    parser.content = inputContent
    parser.downloadData()
  }

  const extraData = (input: string) => {
    const regex = /<tw-storydata([^>]*)>([\s\S]*?)<\/tw-storydata>/g;
    const matches = [];
    let match;

    while ((match = regex.exec(input)) !== null) {
      // match[0] 匹配整个标签及其内容
      // match[1] 匹配标签中的内容（不包括标签本身）
      matches.push(match[0]);
    }
    return matches[0]
  }

  const handleLoadFromFile = () => {
    if (!curFile) {
      return;
    }
    const reader = new FileReader();
    // 添加load事件监听器，以便在文件读取完成时触发
    reader.addEventListener('load', (e) => {
      // 读取的文件数据位于e.target.result中
      const fileData = e.target?.result;
      setInputContent(extraData(fileData))
    });
    // 读取文件数据
    reader.readAsText(curFile.originFileObj);
  }

  return <>
    <ProCard gutter={[16, 16]}>
      说明: 将twine编辑之后的内容转换为csv配置表格式，直接选择文件或者将导出的内容赋值到左侧
    </ProCard>
    <ProCard gutter={[16, 16]}>
      <ProCard colSpan="40%" 
        title="输入"
        headerBordered 
        bordered
        extra={
          <Space>
          {curFileName}
          <Button onClick={handleLoadFromFile}>加载</Button>
          <Upload
            name='file'
            maxCount={1}
            onChange={handleChangeFile}
            itemRender={(originNode, file, fileList, actions) => {
              return <></>
            }}
          >
            <Button icon={<UploadOutlined />}>Upload</Button>
          </Upload>
          </Space>
        }
      >
      <TextArea rows={20} value={inputContent}/>
      </ProCard>
      <ProCard 
        bordered
        title="输出"
        headerBordered
        extra={
          <Space>
            <Button onClick={readToCsvData}>
              读取
            </Button>
            <Button onClick={downloadCsvData}>
              下载
            </Button>
          </Space>
        }
      >
        <TextArea rows={20} value={outputContent}/>
      </ProCard>
    </ProCard>
  </>
}